package com.hmy.finance.common.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 基于Springboot的redisTemplate使用setIfAbsent实现Redis分布式锁
 *
 * @author songkf
 */
public class RedisDistributedLock {

    private final StringRedisTemplate redisTemplate;
    private final String lockKey;
    private final String lockValue;

    public RedisDistributedLock(StringRedisTemplate redisTemplate, String lockKey) {
        this.redisTemplate = redisTemplate;
        this.lockKey = lockKey;
        // 生成唯一的锁标识
        this.lockValue = UUID.randomUUID().toString();
    }

    /**
     * 尝试获取锁
     *
     * @param expireTime 锁的过期时间，单位为秒
     * @return 是否成功获取锁
     */
    public boolean tryLock(long expireTime) {
        return Boolean.TRUE.equals(redisTemplate.opsForValue().setIfAbsent(lockKey, lockValue, expireTime, TimeUnit.SECONDS));
    }

    /**
     * 释放锁
     */
    public void unlock() {
        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
        String value = valueOperations.get(lockKey);
        if (value != null && value.equals(lockValue)) {
            // 只有当锁的值匹配时，才执行删除操作，释放锁
            valueOperations.getOperations().delete(lockKey);
        }
    }
}
